package com.alaoks.uploadfile.controller;

import com.alaoks.uploadfile.entity.Message;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@RestController
public class UploadController {

    @PostMapping("/upload")
    public Object upmethod(
            @RequestParam(value="directory") String dir,
            @RequestParam("fileUpload")MultipartFile file
    ){
        //获取文件名
        String fileName=file.getOriginalFilename();
        //获取后缀名
        String suffixName=fileName.substring((fileName.lastIndexOf(".")));
        //生成不重复的文件名
        //fileName= UUID.randomUUID()+suffixName;
        //指定存储地址
        String filePath="/spb/csupload/";
        //创建文件夹
        mikdir(filePath+dir);
        try {
            file.transferTo(new File(filePath+dir+"/"+fileName));
            return new Message(200,"success to upload");
        }catch (Exception e){
            e.printStackTrace();
            return new Message(400,"fail to upload:");
        }
    }

    private void mikdir(String filepath){
        File file=new File(filepath);
        if(file.exists()&&file.isDirectory())
            return;
        if (file.exists()) {
            file.delete();
            file.mkdirs();
        } else {
            file.mkdirs();
        }
    }
}
